package com.example.sy.control;

import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

//上传文件
@RestController
public class uploadFile {
    private static final String UPLOAD_DIR = "src/main/resources/static/upload/";

    @PostMapping("/uploadFile")
    public Map<Object, String> upload(@RequestParam("file") MultipartFile file) {
        Map<Object, String> map = new HashMap<>();
        if (file.isEmpty()) {
            map.put("code", "500");
            map.put("msg", "上传失败");
        }
        if (!file.isEmpty()) {
            try {
                Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename());
                String fileName = file.getOriginalFilename();
                //创建父级目录去存取
                Files.createDirectories(path.getParent());
                //file 存取位置
                file.transferTo(path);
                map.put("code", "200");
                map.put("msg", "success");
            } catch (Exception e) {
                e.printStackTrace();
                map.put("code", "500");
                map.put("msg", "上传失败");
            }
        }
        return map;
    }
}
